import des from "../../utils/des";
const dayjs = require("dayjs");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      form_value1: '',
      form_value1_index: 0,
      form_value2: '',
      form_value3: '',
      form_value4: '',
      form_value5: dayjs(new Date()).format('YYYY-MM-DD'),
      form_value6: '0',
      form_value7: '0',
      form_value8: '0',
      form_value9: '',
      form_value10: '0',
      form_value11: '0',
      form_value12: '0',
      form_value13: '10次以下',
      form_value14: '',
      form_value15: '',
      form_value16: '',
    },
    phone: wx.getStorageSync('userInfo').phone || '',
    pickerList1: [
      '昆山市',
      '姑苏区',
      '太仓市',
      '吴中区',
      '吴江区',
      '工业园区',
      '张家港市',
      '相城区',
      '常熟市',
      '高新区'
    ],
    pickerList2: [
      {
        id: '',
        name: '中国工商银行'
      },
      {
        id: '',
        name: '中国农业银行'
      },
      {
        id: '',
        name: '中国银行'
      },
      {
        id: '',
        name: '中国建设银行'
      },
      {
        id: '',
        name: '交通银行'
      },
      {
        id: '',
        name: '中国邮政储蓄银行'
      },
      {
        id: '',
        name: '招商银行'
      },
      {
        id: '',
        name: '兴业银行'
      },
      {
        id: '',
        name: '网商银行'
      },
      {
        id: '',
        name: '微众银行'
      },
      {
        id: '',
        name: '不予告知'
      },
    ],
    pickerList3: [
      '10次以下',
      '10-50次',
      '50次以上'
    ],
    pickerList4: [
      '不能接受',
      '一般',
      '能接受'
    ],
    fileList: [],
    showSuccess: false,
    id: '',
    type: '',
    merchantName: ''
  },

  selectSq () {
    if (!this.data.form.form_value1) {
      wx.showToast({
        title: '请先选择巡检板块',
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: `/sub_xunjian/businessCircle/businessCircle?region=${this.data.form.form_value1}`
      })
    }
  },
  inputValue1 (e) {
    this.setData({
      ['form.form_value3']: e.detail.value
    })
  },
  inputValue2 (e) {
    this.setData({
      ['form.form_value4']: e.detail.value
    })
  },
  inputValue22 (e) {
    this.setData({
      ['form.form_value2']: e.detail.value
    })
  },
  inputValue3 (e) {
    this.setData({
      ['form.form_value14']: e.detail.value
    })
  },
  inputValue4 (e) {
    this.setData({
      ['form.form_value16']: e.detail.value
    })
  },
  onChange1 (e) {
    const id = +e.detail.value
    const name = this.data.pickerList1[id]
    this.setData({
      ['form.form_value1']: name
    })
    // console.log(this.data.form, 'form')
  },
  onChange2 (e) {
    this.setData({
      ['form.form_value5']: e.detail.value
    })
  },
  onChange3 (e) {
    const id = +e.detail.value
    const name = this.data.pickerList2[id].name
    this.setData({
      ['form.form_value9']: name
    })
    // console.log(this.data.form, 'form')
  },
  onChange4 (e) {
    const id = +e.detail.value
    const name = this.data.pickerList3[id]
    this.setData({
      ['form.form_value13']: name
    })
    // console.log(this.data.form, 'form')
  },
  onChange5 (e) {
    const id = +e.detail.value
    const name = this.data.pickerList4[id]
    this.setData({
      ['form.form_value15']: name
    })
    // console.log(this.data.form, 'form')
  },
  checkboxChange (e) {
    this.setData({
      [`form.${e.currentTarget.dataset.key}`]: this.data.form[e.currentTarget.dataset.key] == '0' ? '1' : '0'
    })
    console.log(this.data.form, 'form')
  },

  goBack () {
    if (this.data.type == '1') {
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.setData({ // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
        needFresh: true
      })
      wx.navigateBack({
        delta: 1 // 返回上一级页面。
      })
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },

  selectSh() {
    wx.navigateTo({
      url: '/sub_xunjian/nearbyMerchants/nearbyMerchants'
    })
  },

  async commitBasicInfo () {
    if (this.data.type == '1') {
      this.editCommit()
    } else {
      this.newCommit()
    }
  },
  async newCommit () {
    // 校验填写信息
    if (this.verifyForm()) {
      const params = {
        accept: this.data.form.form_value15,
        bankName: this.data.form.form_value9,
        cbdName: this.data.form.form_value2,
        digitalRmb: this.data.form.form_value8,
        effect: this.data.form.form_value14,
        frequency: this.data.form.form_value13,
        payMents: this.data.form.form_value6 + ',' + this.data.form.form_value7,
        picturesList: this.data.fileList.map(val => val.url),
        region: this.data.form.form_value1,
        service: this.data.form.form_value10 + ',' + this.data.form.form_value11 + ',' + this.data.form.form_value12,
        storeName: this.data.form.form_value4,
        surveyTime: this.data.form.form_value5,
        userId: wx.getStorageSync('userInfo').userId,
        userName: this.data.form.form_value3,
        remark: this.data.form.form_value16
      }
      console.log(params, 'params')
      // /bcInspection/insertSurveyInfo
      const res = await getApp().globalData.request(
        "/bcInspection/insertSurveyInfo",
        params,
        "POST"
      );
      console.log(res, '巡检提交的返回')
      if (res.code == 200) {
        this.setData({
          showSuccess: true
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }
  },
  async editCommit () {
    // 校验填写信息
    if (this.verifyForm()) {
      const params = {
        accept: this.data.form.form_value15,
        bankName: this.data.form.form_value9,
        cbdName: this.data.form.form_value2,
        digitalRmb: this.data.form.form_value8,
        effect: this.data.form.form_value14,
        frequency: this.data.form.form_value13,
        payMents: this.data.form.form_value6 + ',' + this.data.form.form_value7,
        picturesList: this.data.fileList.map(val => val.url),
        region: this.data.form.form_value1,
        service: this.data.form.form_value10 + ',' + this.data.form.form_value11 + ',' + this.data.form.form_value12,
        storeName: this.data.form.form_value4,
        surveyTime: this.data.form.form_value5,
        userId: wx.getStorageSync('userInfo').userId,
        userName: this.data.form.form_value3,
        id: this.data.id,
        remark: this.data.form.form_value16
      }
      console.log(params, 'params')
      // 特殊处理图片为空
      // if(params.picturesList.length === 0) {
      //   params.picturesList.push('cxgc')
      // }
      const res = await getApp().globalData.request(
        "/bcInspection/updateSurveyInfo",
        params,
        "POST"
      );
      console.log(res, '巡检提交的返回')
      if (res.code == 200) {
        this.setData({
          showSuccess: true
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }
  },
  verifyForm () {
    if (!this.data.form.form_value1) {
      wx.showToast({
        title: '请选择巡检板块',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value2) {
      wx.showToast({
        title: '请选择巡检商圈',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value3) {
      wx.showToast({
        title: '请输入巡检人',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value4) {
      wx.showToast({
        title: '请输入商户名称',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value5) {
      wx.showToast({
        title: '请选择巡检时间',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value9) {
      wx.showToast({
        title: '请选择受理银行',
        icon: 'none'
      })
      return false
    }
    // if (!this.data.form.form_value14) {
    //   wx.showToast({
    //     title: '请填写活动效果',
    //     icon: 'none'
    //   })
    //   return false
    // }
    if (!this.data.form.form_value13) {
      wx.showToast({
        title: '请选择商户受理频次',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.form_value15) {
      wx.showToast({
        title: '请选择接受程度',
        icon: 'none'
      })
      return false
    }
    // if (!this.data.form.form_value16) {
    //   wx.showToast({
    //     title: '请填写备注',
    //     icon: 'none'
    //   })
    //   return false
    // }
    return true
  },
  deleteImg (e) {
    // console.log(e, 'eeeeee')
    // wx.showLoading({
    //   title: '正在删除...',
    // })
    this.data.fileList.splice(e.detail.index, 1)
    this.setData({
      fileList: this.data.fileList,
    })
    getApp().globalData.request("/api/fileApi/cosDelete", {
      url: e.detail.file.url
    }, "POST").then(res => {
      // console.log(res);
      // wx.hideLoading()
      // if (res.code == 200) {
      //   wx.showToast({
      //     title: res.data,
      //   })
      // } else {
      //   wx.showToast({
      //     title: res.data,
      //   })
      // }
    })
  },
  selectImg () {
    var that = this
    wx.chooseMedia({
      count: 6,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 6,
      camera: 'back',
      sizeType: ['original', 'compressed'],
      success (res) {
        console.log(res);
        const tempFilePaths = res.tempFiles
        // tempFilePaths.forEach( poio => {
        //   that.data.fileList.push({
        //     url: poio.tempFilePath,
        //     deletable: true,
        //   })
        // })
        // that.setData({
        //   fileList: that.data.fileList,
        // })
        console.log(tempFilePaths, 'tempFilePaths')
        // 上传文件 
        wx.showLoading({
          title: '上传中',
        })
        that.upImages(tempFilePaths)
      }
    })
  },
  async upImages (tempFilePaths) {
    let urlList = []
    for (let index = 0; index < tempFilePaths.length; index++) {
      const res = await this.uploadImage(tempFilePaths[index])
      console.log(res, '上传返回的结果')
      urlList.push({
        url: res,
        deletable: true
      })
    }
    wx.hideLoading()
    this.setData({
      fileList: this.data.fileList.concat(urlList)
    })
  },
  afterRead (e) {
    // console.log(e, '上传返回的临时结果')
    let list = []
    e.detail.file.forEach(pre=>{
      list.push({
        size: pre.size,
        tempFilePath: pre.url,
        type: pre.type
      })
    })
    this.upImages(list)
  },
  // 图片上传
  uploadImage (infos) {
    console.log(infos, '123213213213213')
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://fintech-wx.szjrgzjg.com/api/fileApi/cosUpload',
        filePath: infos.tempFilePath,
        name: 'file',
        formData: {
          file: infos,
          folder: 'mini_xunjian'
        },
        header: {
          token: wx.getStorageSync("token")
        },
        success (res) {
          var data = des.decrypt(
            JSON.parse(res.data).data,
            "98fbffd1064a4355b8abaacb6fa96f94"
          );
          console.log(JSON.parse(data));
          resolve(JSON.parse(data).data)
        },
        fail (err) {
          reject(err);
        }
      })
    })
  },
  async getDetails () {
    const params = {
      id: this.data.id
    }
    const res = await getApp().globalData.request(
      "/bcInspection/getSurvey",
      params,
      "POST"
    );
    if (res.code == 200 && res.data) {
      console.log(res, 'res')
      // 反显数据
      this.setData({
        ['form.form_value1']: res.data.region,
        ['form.form_value1_index']: 0,
        ['form.form_value2']: res.data.cbdName,
        ['form.form_value3']: res.data.userName,
        ['form.form_value4']: res.data.storeName,
        ['form.form_value5']: res.data.surveyTime,
        ['form.form_value6']: res.data.payMents.split(',')[0],
        ['form.form_value7']: res.data.payMents.split(',')[1],
        ['form.form_value8']: res.data.digitalRmb,
        ['form.form_value9']: res.data.bankName,
        ['form.form_value10']: res.data.service.split(',')[0],
        ['form.form_value11']: res.data.service.split(',')[1],
        ['form.form_value12']: res.data.service.split(',')[2],
        ['form.form_value13']: res.data.frequency,
        ['form.form_value14']: res.data.effect,
        ['form.form_value15']: res.data.accept,
        ['form.form_value16']: res.data.remark,
      })
      // 处理图片的反显
      if (res.data.pictures && res.data.pictures.split(',').length > 0) {
        res.data.pictures.split(',').forEach(pre => {
          if(pre !== 'cxgc') {
            this.data.fileList.push({
              url: pre,
              deletable: true
            })
          }
        })
        this.setData({
          fileList: this.data.fileList
        })
      }
    }
  },
  async getPreInfos () {
    const params = {
      userId: wx.getStorageSync('userInfo').userId
    }
    console.log(params, 'getNewSurvey')
    const res = await getApp().globalData.request(
      "/bcInspection/getNewSurvey",
      params,
      "POST"
    );
    if (res.code == 200 && res.data) {
      console.log(res, 'res')
      // 反显数据
      this.setData({
        ['form.form_value1']: res.data.region,
        ['form.form_value1_index']: 0,
        ['form.form_value2']: res.data.cbdName,
        ['form.form_value3']: res.data.userName,
        ['form.form_value4']: '',
        // ['form.form_value5']: res.data.surveyTime,
        ['form.form_value6']: res.data.payMents.split(',')[0],
        ['form.form_value7']: res.data.payMents.split(',')[1],
        ['form.form_value8']: res.data.digitalRmb,
        ['form.form_value9']: res.data.bankName,
        ['form.form_value10']: res.data.service.split(',')[0],
        ['form.form_value11']: res.data.service.split(',')[1],
        ['form.form_value12']: res.data.service.split(',')[2],
        ['form.form_value13']: res.data.frequency,
        ['form.form_value14']: res.data.effect,
        ['form.form_value15']: res.data.accept,
        ['form.form_value16']: res.data.remark,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow () {
    if (this.data.name) {
      this.setData({
        ['form.form_value2']: this.data.name
      })
    }
    if(this.data.merchantName) {
      this.setData({
        ['form.form_value4']: this.data.merchantName
      })
    }
  },

  onLoad (options) {
    const id = options.id
    const type = options.type || ''
    this.setData({
      id: id,
      type: type
    })
    if (id) {
      wx.setNavigationBarTitle({
        title: type == '2' ? '巡检详情' : '修改'
      })
      // 查找详情
      this.getDetails()
    } else {
      wx.setNavigationBarTitle({
        title: '新建巡检'
      })
      // 获取上次提交的记录
      this.getPreInfos()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () { },
});
